<template>
  <div class="task-view">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>地铁隧道巡线车智能巡检系统</el-breadcrumb-item>
      <el-breadcrumb-item>任务列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 顶部右侧数据库开关 -->
    <el-switch
        v-model="settingStore.useDb"
        class="db-switcher"
        active-text="读取数据库"
        inactive-text="实时模式"
        @change="handleDbSwitch"
    />

    <!-- 可视化大屏跳转按钮 -->
    <el-button
        type="primary"
        class="screen-btn"
        @click="goBigScreen"
    >📊 大屏</el-button>

    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="任务编号">
          <el-input v-model="queryParams.taskCode" placeholder="请输入任务编号" @keyup.enter="handleSearch" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="queryParams.creator" placeholder="请输入创建人" @keyup.enter="handleSearch" clearable></el-input>
        </el-form-item>
        <el-form-item label="执行人">
          <el-input v-model="queryParams.executor" placeholder="请输入执行人" @keyup.enter="handleSearch" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.taskStatus" style="width: 100px;" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待巡视" value="待巡视"></el-option>
            <el-option label="巡视中" value="巡视中"></el-option>
            <el-option label="待上传" value="待上传"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="toolbar">
      <el-button type="primary" @click="handleAddTask">📹 新增任务</el-button>
    </div>

    <el-table :data="tableData" stripe v-loading="loading">
      <el-table-column type="index" label="序号" width="55" align="center"/>
      <el-table-column prop="taskCode" label="任务编号" width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="handleTaskCodeClick(row)">{{ row.taskCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="taskName" label="任务名称" />
      <el-table-column prop="startPos" label="起始地点" width="130" />
      <el-table-column prop="taskTrip" label="任务距离" width="130" />
      <el-table-column prop="creator" label="创建人" width="130" />
      <el-table-column prop="executor" label="执行人" width="130" />
      <el-table-column prop="execTime" label="执行时间" width="180" />
      <el-table-column prop="endTime" label="完成时间" width="180" />
      <el-table-column prop="taskStatus" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.taskStatus)">{{ row.taskStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template #default="{ row }">
          <el-button v-if="row.taskStatus === '已完成'" link type="primary" @click="handleView(row)">查看</el-button>
          <div v-if="row.taskStatus === '待巡视'">
            <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </div>
          <el-button v-if="row.taskStatus === '待上传'" link type="primary" @click="handleUpload(row)">上传</el-button>
          <el-button v-if="row.taskStatus === '巡视中'" link type="primary" @click="handleView(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        class="pagination"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="getList"
        @current-change="getList"
    />

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
      <el-form :model="taskForm" label-width="100px" ref="taskFormRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" maxlength="50" :disabled="isViewMode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="taskForm.taskCode" placeholder="请输入任务编号" maxlength="20" :disabled="isViewMode || dialogMode === 'add'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起始地点" prop="startPos">
              <el-input v-model="taskForm.startPos" placeholder="请输入起始地点" :disabled="isViewMode">
                <template #append>M</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务距离" prop="taskTrip">
              <el-input v-model="taskForm.taskTrip" placeholder="请输入任务距离" :disabled="isViewMode">
                <template #append>M</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建人" prop="creator">
              <el-input v-model="taskForm.creator" placeholder="请输入创建人" maxlength="10" :disabled="isViewMode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="executor">
              <el-input v-model="taskForm.executor" placeholder="请输入执行人" maxlength="10" :disabled="isViewMode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="taskForm.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="250" :disabled="isViewMode"></el-input>
        </el-form-item>

        <el-alert v-if="dialogMode === 'edit'" title="点击下方[启动]按钮后巡线车将开始工作，请确保车辆周围环境安全。" type="warning" show-icon :closable="false" />

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="handleSave" :loading="saving">确定</el-button>
          <el-button v-if="dialogMode === 'edit'" type="success" @click="handleStart" :loading="saving">启动</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { listTask, addTask, updateTask, delTask, startTask, uploadTask, upsertTaskDb } from '@/axios/api';
import type { AgvTask } from '@/axios/types';
import router from '@/router';
import { useSetting } from '@/stores/setting';

const loading = ref(false);
const saving = ref(false);
const total = ref(0);
const tableData = ref<AgvTask[]>([]);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  orderByColumn:'id',
  isAsc: 'desc',
});

const settingStore = useSetting();

const getList = async () => {
  loading.value = true;
  try {
    const res = await listTask(queryParams);
    console.log(res)
    tableData.value = res.rows;
    total.value = res.total;

    // 同步任务信息到本地 DB（实时模式时）
    if (!settingStore.useDb && Array.isArray(res.rows)) {
      const promises = res.rows.map(item => upsertTaskDb(item));
      Promise.all(promises).catch(err => console.error('同步任务到DB失败', err));
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

const handleReset = () => {
  queryParams.pageNum = 1;
  queryParams.taskCode = '';
  queryParams.creator = '';
  queryParams.executor = '';
  queryParams.taskStatus = '';
  getList();
};

const getStatusType = (status: string) => {
  switch (status) {
    case '已完成': return 'success';
    case '待巡视': return 'warning';
    case '巡视中': return 'primary';
    case '待上传': return 'info';
    default: return 'info';
  }
};

// --- Dialog ---
const dialogVisible = ref(false);
const dialogTitle = ref('新增任务');
const dialogMode = ref('add'); // 'add', 'edit', 'view'
const isViewMode = computed(() => dialogMode.value === 'view');
const taskFormRef = ref<FormInstance>();

const initialForm: AgvTask = {
  id: null,
  taskName: '',
  taskCode: '',
  startPos: '',
  taskTrip: '',
  creator: '',
  executor: '',
  remark: '',
  taskStatus: '待巡视'
};

const taskForm = ref<AgvTask>({ ...initialForm });

const rules = reactive<FormRules>({
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  taskCode: [{ required: true, message: '请输入任务编号', trigger: 'blur' }],
  startPos: [{ required: true, message: '请输入起始地点', trigger: 'blur' }, { pattern: /^\d+(\.\d+)?$/, message: '必须为数字', trigger: 'blur' }],
  taskTrip: [{ required: true, message: '请输入任务距离', trigger: 'blur' }, { pattern: /^\d+(\.\d+)?$/, message: '必须为数字', trigger: 'blur' }],
  creator: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
  executor: [{ required: true, message: '请输入执行人', trigger: 'blur' }],
});


const resetForm = () => {
  taskForm.value = { ...initialForm };
  taskFormRef.value?.resetFields();
};

const handleAddTask = () => {
  resetForm();
  dialogMode.value = 'add';
  dialogTitle.value = '新增任务';

  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  taskForm.value.taskCode = `TASK-${year}${month}${day}${hours}${minutes}${seconds}`;

  dialogVisible.value = true;
};

const handleEdit = (row: AgvTask) => {
  resetForm();
  dialogMode.value = 'edit';
  dialogTitle.value = '修改任务';
  taskForm.value = { ...row };
  dialogVisible.value = true;
};

const handleTaskCodeClick = (row: AgvTask) => {
  switch (row.taskStatus) {
    case '待巡视':
      handleEdit(row);
      break;
    case '巡视中':
      router.push('/task/execute/' + row.id);
      break;
    default: // 已完成、待上传等
      router.push('/task/detail/' + row.id);
  }
};

const handleView = (row: AgvTask) => {
  if (row.taskStatus === '巡视中') {
    router.push('/task/execute/' + row.id);
  } else {
    router.push('/task/detail/' + row.id);
  }
};

const handleDelete = (row: AgvTask) => {
  ElMessageBox.confirm(`确定要删除任务 "${row.taskName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    if (row.id) {
      await delTask(row.id);
      ElMessage.success('删除成功');
      await getList();
    }
  }).catch(() => {});
};

const handleUpload = (row: AgvTask) => {
  ElMessageBox.confirm(`确定要上传任务 "${row.taskName}" 的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  }).then(async () => {
    if (row.id) {
      await uploadTask(row.id);
      ElMessage.success('已开始上传');
      await getList();
    }
  }).catch(() => {});
};

const handleSave = async () => {
  if (!taskFormRef.value) return;
  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      try {
        if (dialogMode.value === 'add') {
          const res = await addTask(taskForm.value);
          const newId = res?.data?.id ?? res?.data;
          ElMessage.success('新增成功');
          ElMessageBox.confirm('任务已创建，是否立即启动巡检任务？', '提示', {
            confirmButtonText: '启动',
            cancelButtonText: '稍后',
            type: 'warning',
          }).then(async () => {
            if (newId) {
              await startTask(newId);
              ElMessage.success('任务已启动');
            }
          }).catch(() => {});
        } else {
          await updateTask(taskForm.value);
          ElMessage.success('修改成功');
        }
        dialogVisible.value = false;
        await getList();
      } finally {
        saving.value = false;
      }
    }
  });
};

const handleStart = async () => {
  if (!taskForm.value.id) return;
  saving.value = true;
  try {
    await startTask(taskForm.value.id);
    ElMessage.success('任务已启动');
    dialogVisible.value = false;
    await getList();
  } finally {
    saving.value = false;
  }
};

const handleDbSwitch = () => {
  queryParams.pageNum = 1;
  getList();
};

// 跳转到可视化大屏
const goBigScreen = () => {
  router.push('/dashboard');
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.task-view {
  padding: 20px;
  position: relative;
}
.search-card {
  margin-top: 20px;
}
.toolbar {
  margin: 20px 0;
}
.pagination {
  margin-top: 20px;
  justify-content: center;
}
.db-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
}
.screen-btn {
  position: absolute;
  top: 20px;
  right: 140px; /* 位于数据库开关左侧 */
  margin-right: 80px;
}
</style>